import dayjs from "dayjs";
import editForm from "../form.vue";
import batchForm from "../batch-form.vue";
import processForm from "../process.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "@/views/system/hooks";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps, ProcessFormItemProps } from "./types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {
  waRechargeApi,
  waAccountApi,
  type WaRechargeForm,
  type SearchParams,
  WA_RECHARGE_STATES,
  WA_RECHARGE_STATE_COLORS,
  WA_RECHARGE_STATE_TEXTS
} from "@/api/whatsapp";
import { type Ref, reactive, ref, onMounted, h, toRaw } from "vue";
import { DocumentCopy } from "@element-plus/icons-vue";

export function useWaRecharge(tableRef: Ref) {
  const form = reactive<SearchParams>({
    account_id: undefined,
    state: undefined,
    creator_id: undefined,
    amount: undefined,
    remark: "",
    time: []
  });

  const formRef = ref();
  const processFormRef = ref();
  const dataList = ref([]);
  const accountList = ref([]);
  const userList = ref([]);
  const stateOptions = ref([]);
  const searchCondArr = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle, tagStyle } = usePublicHooks();
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    pageSizes: [20, 40, 60, 100, 300, 500],
    currentPage: 1,
    background: true
  });

  // 复制账号功能
  const copyAccount = async (account: string) => {
    // 如果第一个数字是1，只复制第二位开始的内容；否则复制全部内容
    const copyText = account && account.charAt(0) === '1' ? account.substring(1) : account;
    
    try {
      await navigator.clipboard.writeText(copyText);
      message("账号已复制到剪贴板", { type: "success" });
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const columns: TableColumnList = [
    {
      type: "selection",
      width: 40,
      align: "center",
      selectable: (row) => row.state === WA_RECHARGE_STATES.PENDING
    },
    {
      label: "编号",
      prop: "id",
      width: 60
    },
    {
      label: "WhatsApp账号",
      prop: "wa_account",
      minWidth: 150,
      cellRenderer: ({ row, props }) => (
        <div style="display: flex; align-items: center; gap: 8px;">
          <span>{row.wa_account}</span>
          <el-button
            icon={DocumentCopy}
            size="small"
            type="primary"
            link
            title="点击复制账号"
            onClick={() => copyAccount(row.wa_account)}
          />
        </div>
      )
    },
    {
      label: "账号备注",
      prop: "wa_account_remark",
      minWidth: 120,
      width: 150,
      showOverflowTooltip: true,
      formatter: (row, column, cellValue) => {
        return cellValue ? cellValue : '-';
      }
    },
    {
      label: "充值金额",
      prop: "amount",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <span style="color: #f56c6c; font-weight: bold;">
          {row.amount}
        </span>
      )
    },
    {
      label: "申请备注",
      prop: "remark",
      width: 150,
      showOverflowTooltip: true,
      formatter: (row, column, cellValue) => {
        return cellValue ? cellValue : '-';
      }
    },
    {
      label: "申请人",
      prop: "creator_name",
      minWidth: 100
    },
    {
      label: "申请时间",
      prop: "created_at",
      minWidth: 160
    },
    {
      label: "状态",
      prop: "state_text",
      minWidth: 100,
      cellRenderer: scope => (
        <el-tag
          size={scope.props.size === "small" ? "small" : "default"}
          type={WA_RECHARGE_STATE_COLORS[scope.row.state]}
        >
          {scope.row.state_text}
        </el-tag>
      )
    },
    {
      label: "处理人",
      prop: "feedbacker_name",
      minWidth: 100
    },
    {
      label: "反馈内容",
      prop: "feedback_content",
      width: 150,
      showOverflowTooltip: true,
      formatter: (row, column, cellValue) => {
        return cellValue ? cellValue : '-';
      }
    },
    {
      label: "处理时间",
      prop: "feedback_at",
      minWidth: 160,
      cellRenderer: ({ row }) => {
        if (!row.feedback_at || row.feedback_at === null) return '-';
        // 如果是时间戳数字，转换为日期格式
        const timestamp = parseInt(row.feedback_at);
        if (isNaN(timestamp) || timestamp === 0) return '-';
        return dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 280,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    selectedNum.value = val.length;
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const params = {
      ...toRaw(form),
      page: pagination.currentPage,
      limit: pagination.pageSize
    };

    try {
      const { data } = await waRechargeApi.list(params);
      dataList.value = data.data;  // Laravel分页结构中数据在data.data中
      pagination.total = data.total;
      pagination.currentPage = data.current_page;
      pagination.pageSize = data.per_page;
      accountList.value = data.wa_account_options || data.account_list || [];
      userList.value = data.user_list || [];
      stateOptions.value = data.state_options || [];
      searchCondArr.value = data.search_cond_arr || [];
    } catch (error) {
      console.error("获取申请列表失败:", error);
      message("获取申请列表失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function chores(curData, res, title, done) {
    if (res.code === 0) {
      message(`您${title}了充值申请`, {
        type: "success"
      });
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    } else {
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}充值申请`,
      props: {
        formInline: {
          account_id: row?.account_id ?? undefined,
          amount: row?.amount ?? 0,
          remark: row?.remark ?? "",
          accountList: accountList.value
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as WaRechargeForm;

        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              waRechargeApi.create(curData).then(res => chores(curData, res, title, done));
            } else {
              waRechargeApi.update(row.id, curData).then(res => chores(curData, res, title, done));
            }
          }
        });
      }
    });
  }

  function openProcessDialog(row: FormItemProps) {
    addDialog({
      title: `处理充值申请 - ${row.wa_account}`,
      props: {
        formInline: {
          id: row.id,
          wa_account: row.wa_account,
          amount: row.amount,
          creator_name: row.creator_name,
          created_at_text: row.created_at,
          remark: row.remark,
          state: WA_RECHARGE_STATES.APPROVED,
          feedback_content: ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(processForm, { ref: processFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = processFormRef.value.getRef();
        const curData = options.props.formInline as ProcessFormItemProps;

        FormRef.validate(valid => {
          if (valid) {
            waRechargeApi.process(row.id, {
              state: curData.state,
              feedback_content: curData.feedback_content
            }).then(res => {
              if (res.code === 0) {
                message(res.data.message || "处理成功", { type: "success" });
                done();
                onSearch();
              } else {
                message(`处理失败，${res.message}`, { type: "error" });
              }
            });
          }
        });
      }
    });
  }

  function openBatchDialog() {
    const batchFormRef = ref();
    
    addDialog({
      title: "批量充值申请",
      props: {
        formInline: {
          user_id: undefined,
          userList: userList.value,
          accountList: accountList.value,
          remark: ""
        }
      },
      width: "70%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(batchForm, { ref: batchFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = batchFormRef.value.getRef();
        
        FormRef.validate(valid => {
          if (valid) {
            try {
              const formData = batchFormRef.value.getFormData();
              
              waRechargeApi.batchCreate(formData).then(res => {
                if (res.code === 0) {
                  const results = res.data.results;
                  if (results && results.errors && results.errors.length > 0) {
                    // 有部分失败的情况，显示详细错误
                    console.warn('批量申请部分失败:', results.errors);
                    ElMessageBox.alert(
                      results.errors.join('\n'),
                      '批量申请结果',
                      {
                        confirmButtonText: '确定',
                        type: 'warning',
                        dangerouslyUseHTMLString: false
                      }
                    );
                  }
                  message(res.data.message || "批量申请成功", { type: "success" });
                  done();
                  onSearch();
                } else {
                  message(`批量申请失败：${res.message}`, { type: "error" });
                }
              }).catch(error => {
                console.error('批量申请失败:', error);
                message("批量申请失败，请稍后重试", { type: "error" });
              });
            } catch (error) {
              message(error.message, { type: "error" });
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    try {
      const result = await ElMessageBox.confirm(
        `确认要删除申请编号"${row.id}"吗？`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      if (result === "confirm") {
        const res = await waRechargeApi.delete(row.id);
        if (res.code === 0) {
          message(`删除申请成功`, { type: "success" });
          onSearch();
        } else {
          message(`删除失败，${res.message}`, { type: "error" });
        }
      }
    } catch (error) {
      console.log("用户取消删除");
    }
  }

  async function handleBatchProcess(action: 'approve' | 'reject') {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (curSelected.length === 0) {
      message("请先选择要处理的申请", { type: "warning" });
      return;
    }

    const pendingSelected = curSelected.filter(item => item.state === WA_RECHARGE_STATES.PENDING);
    if (pendingSelected.length === 0) {
      message("选择的申请中没有待处理的记录", { type: "warning" });
      return;
    }

    const actionText = action === 'approve' ? '批量充值' : '批量驳回';

    try {
      let feedbackContent = '';

      if (action === 'reject') {
        const { value } = await ElMessageBox.prompt(
          `请输入驳回原因`,
          actionText,
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputType: "textarea",
            inputValidator: (value) => {
              if (!value || value.trim() === '') {
                return '驳回原因不能为空';
              }
              return true;
            }
          }
        );
        feedbackContent = value;
      } else {
        const result = await ElMessageBox.confirm(
          `确认要${actionText} ${pendingSelected.length} 个申请吗？`,
          actionText,
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        );

        if (result !== "confirm") return;
      }

      const res = await waRechargeApi.batchProcess({
        ids: pendingSelected.map(item => item.id),
        state: action === 'approve' ? WA_RECHARGE_STATES.APPROVED : WA_RECHARGE_STATES.REJECTED,
        feedback_content: feedbackContent
      });

      if (res.code === 0) {
        message(res.data.message || `${actionText}成功`, { type: "success" });
        onSearch();
      } else {
        message(`${actionText}失败，${res.message}`, { type: "error" });
      }
    } catch (error) {
      console.log(`用户取消${actionText}`);
    }
  }

  async function handleBatchMarkRecharged() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (curSelected.length === 0) {
      message("请先选择要标记的申请", { type: "warning" });
      return;
    }

    const pendingSelected = curSelected.filter(item => item.state === WA_RECHARGE_STATES.PENDING);
    if (pendingSelected.length === 0) {
      message("选择的申请中没有待处理的记录", { type: "warning" });
      return;
    }

    try {
      const result = await ElMessageBox.confirm(
        `确认要标记 ${pendingSelected.length} 个申请为已充值吗？`,
        "批量标记已充值",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      if (result === "confirm") {
        const res = await waRechargeApi.batchProcess({
          ids: pendingSelected.map(item => item.id),
          state: WA_RECHARGE_STATES.APPROVED,
          feedback_content: '批量标记已充值'
        });

        if (res.code === 0) {
          message(res.data.message || "批量标记已充值成功", { type: "success" });
          onSearch();
        } else {
          message(`批量标记失败，${res.message}`, { type: "error" });
        }
      }
    } catch (error) {
      console.log("用户取消批量标记");
    }
  }

  async function handleBatchDelete() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (curSelected.length === 0) {
      message("请先选择要删除的申请", { type: "warning" });
      return;
    }

    const pendingSelected = curSelected.filter(item => item.state === WA_RECHARGE_STATES.PENDING);
    if (pendingSelected.length === 0) {
      message("只能删除待处理状态的申请", { type: "warning" });
      return;
    }

    try {
      const result = await ElMessageBox.confirm(
        `确认要删除选中的 ${pendingSelected.length} 个申请吗？`,
        "批量删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      if (result === "confirm") {
        let successCount = 0;
        let errorCount = 0;

        for (const item of pendingSelected) {
          try {
            const res = await waRechargeApi.delete(item.id);
            if (res.code === 0) {
              successCount++;
            } else {
              errorCount++;
            }
          } catch (error) {
            errorCount++;
          }
        }

        message(`批量删除完成：成功${successCount}个，失败${errorCount}个`, {
          type: successCount > 0 ? "success" : "error"
        });
        onSearch();
      }
    } catch (error) {
      console.log("用户取消批量删除");
    }
  }

  async function handleBatchCopyAccounts() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (curSelected.length === 0) {
      message("请先选择要复制的申请", { type: "warning" });
      return;
    }

    try {
      // 提取所有选中项的账号，并过滤首个1字符
      const accounts = curSelected.map(item => {
        const account = item.wa_account;
        return account && account.charAt(0) === '1' ? account.substring(1) : account;
      }).filter(account => account); // 过滤空值

      if (accounts.length === 0) {
        message("选中的申请中没有有效的账号", { type: "warning" });
        return;
      }

      // 用换行符连接多个账号
      const copyText = accounts.join('\n');
      
      await navigator.clipboard.writeText(copyText);
      message(`已复制 ${accounts.length} 个账号到剪贴板`, { type: "success" });
    } catch (err) {
      console.error('批量复制失败:', err);
      message("复制失败，请重试", { type: "error" });
    }
  }

  // 检查是否可以编辑/删除
  function canEdit(row) {
    return row.state === WA_RECHARGE_STATES.PENDING;
  }

  // 检查是否可以处理
  function canProcess(row) {
    return row.state === WA_RECHARGE_STATES.PENDING;
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    accountList,
    userList,
    stateOptions,
    searchCondArr,
    pagination,
    selectedNum,
    switchLoadMap,
    switchStyle,
    onSearch,
    resetForm,
    openDialog,
    openBatchDialog,
    openProcessDialog,
    handleDelete,
    handleBatchProcess,
    handleBatchMarkRecharged,
    handleBatchDelete,
    handleBatchCopyAccounts,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    canEdit,
    canProcess,
    WA_RECHARGE_STATES,
    WA_RECHARGE_STATE_TEXTS
  };
}
 